package com.wnxy.sddfp.common;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

public class JwtDemo {
    public static void main(String[] args) {

        // token中存储的数据
        Map<String,Object> payload = new HashMap<>();
        payload.put("id","1000");
        payload.put("name","Jack");

        // 创建密钥对对象
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource("sdd.jks"),"123456".toCharArray());
        KeyPair keyPair = factory.getKeyPair("sdd");
        // 创建签名器; 参数1：加密算法，RSA非对称加密； 参数2：密钥对
        JWTSigner jwtSigner = JWTSignerUtil.createSigner("RSA",keyPair);

        // 1、生成token
        String token = JWTUtil.createToken(payload, jwtSigner);
        System.out.println("token = " + token);

        // 2、验证token
        boolean flag = JWTUtil.verify(token, jwtSigner);
        System.out.println("flag = " + flag);

        // 3、解析token
        if (flag) {
            JWT jwt = JWTUtil.parseToken(token);
            System.out.println("jwt.getPayload(\"id\") = " + jwt.getPayload("id"));
            System.out.println("jwt.getPayload(\"name\") = " + jwt.getPayload("name"));
        }
    }
}
